<template>
  <div class="fd-focal-pane">
    <!--TODO: 设置用户的习惯按钮 -->
    <el-tooltip class="item" content="自定义表格显示列" effect="dark" placement="top">
      <button class="set-fd-cell" @click="setDialogVisible = true"></button>
    </el-tooltip>
    <div class="custom-top">
      <div class="btn">
        <el-link icon="el-icon-folder-checked" @click="fdSaveAll">
          {{ $t('button.submitAfterApprove') }}
        </el-link>
      </div>
      <div class="total-result">
        <table>
          <tr>
            <td>总行数：{{ totalResult.totalLen }}</td>
            |
            <td>当前行数：{{ totalResult.currentLen }}</td>
            |
            <td>Base Price：{{ totalResult.basePrice }}</td>
            |
            <td>GCM Total Cost Delta：{{ totalResult.gcmTotalCostDelta }}</td>
          </tr>
        </table>
      </div>
    </div>
    <div class="custom-bottom">
      <VirtualTable
        :cb="totalCb"
        cbArgs="basePrice,gcmTotalCostDelta"
        :filterable="true"
        :header-cell-style="$headerCellStyle"
        :rowStyle="rowStyle"
        rowKey="fdRowId"
        :table="tableListFilter"
      >
        <!-- rowNo -->
        <Cell fix="left" :label="$t('FdData.rowNo')" :width="50">
          <template slot-scope="scope">
            <span>{{ scope.index + 1 }}</span>
          </template>
        </Cell>
        <!-- basePartName -->
        <Cell
          v-if="cellIsShow.IsFixBasePartName"
          fix="left"
          :label="$t('FdData.basePartName')"
          prop="basePartName"
          sort
          :width="150"
        />
        <!-- basePartNo -->
        <Cell
          v-if="cellIsShow.IsFixBasePartNo"
          fix="left"
          :label="$t('FdData.basePartNo')"
          prop="basePartNo"
          sort
          :width="150"
        />
        <!-- newPartName -->
        <Cell
          v-if="cellIsShow.IsFixNewPartName"
          fix="left"
          :label="$t('FdData.newPartName')"
          prop="newPartName"
          sort
          :width="150"
        />
        <!-- newPartNo -->
        <Cell
          v-if="cellIsShow.IsFixNewPartNo"
          fix="left"
          :label="$t('FdData.newPartNo')"
          prop="newPartNo"
          sort
          :width="150"
        />
        <!-- rdFunction -->
        <Cell
          v-if="cellIsShow.IsRDFunction"
          :label="$t('FdData.rdFunction')"
          prop="rdFunction"
          sort
        />
        <!-- category -->
        <Cell v-if="cellIsShow.IsCategory" :label="$t('FdData.category')" prop="category" sort />
        <!-- itemNo -->
        <Cell v-if="cellIsShow.IsItemNo" :label="$t('FdData.itemNo')" prop="itemNo" sort="number" />
        <!-- rdOwner -->
        <Cell v-if="cellIsShow.IsRDOwner" :label="$t('FdData.rdOwner')" prop="rdOwner" sort />
        <!-- trackingOption -->
        <Cell
          v-if="cellIsShow.IsTrackingOption"
          :label="$t('FdData.trackingOption')"
          prop="trackingOption"
          sort
        />
        <!-- optionType -->
        <Cell v-if="cellIsShow.IsOptionType" :label="$t('FdData.optionType')" prop="optionType" />
        <!-- baseProject -->
        <Cell :label="$t('FdData.baseProject')">
          <!-- basePartName -->
          <Cell
            v-if="cellIsShow.IsBasePartName"
            :label="$t('FdData.basePartName')"
            prop="basePartName"
            sort
            :width="150"
          />
          <!-- basePartNo -->
          <Cell
            v-if="cellIsShow.IsBasePartNo"
            :label="$t('FdData.basePartNo')"
            prop="basePartNo"
            sort
            :width="150"
          />
          <!-- baseMaterialGroup -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialGroup"
            :label="$t('FdData.MaterialGroup')"
            prop="baseMaterialGroup"
            sort
          />
          <!-- baseMaterialDetail -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialDetail"
            :label="$t('FdData.MaterialDetail')"
            prop="baseMaterialDetail"
            sort
          />
          <!-- baseMaterialColor -->
          <Cell
            v-if="cellIsShow.IsBaseMaterialColor"
            :label="$t('FdData.baseMaterialColor')"
            prop="baseMaterialColor"
            sort
          />
          <!-- baseSize -->
          <Cell
            v-if="cellIsShow.IsBaseSize"
            :label="$t('FdData.baseSize')"
            prop="baseSize"
            sort="number"
          />
          <!-- baseQty -->
          <Cell
            v-if="cellIsShow.IsBaseQty"
            :label="$t('FdData.baseQty')"
            prop="baseQty"
            sort="number"
          />
          <!-- baseIdProcess -->
          <Cell
            v-if="cellIsShow.IsBaseIdProcess"
            :label="$t('FdData.baseIdProcess')"
            prop="baseIdProcess"
            sort
          />
          <!-- baseSupplier -->
          <Cell
            v-if="cellIsShow.IsBaseSupplier"
            :label="$t('FdData.baseSupplier')"
            prop="baseSupplier"
            sort
          />
          <!-- baseSupplierPn -->
          <Cell
            v-if="cellIsShow.IsBaseSupplierPn"
            :label="$t('FdData.baseSupplierPn')"
            prop="baseSupplierPn"
            sort
          />
          <!-- baseRemark -->
          <Cell v-if="cellIsShow.IsBaseRemark" :label="$t('FdData.baseRemark')" prop="baseRemark" />
          <!-- baseViewPic -->
          <Cell
            v-if="cellIsShow.IsBaseViewPic"
            :label="$t('FdData.baseViewPic')"
            prop="basePicture"
          >
            <template slot-scope="scope">
              <BaseViewBtn @click="fdPicList(scope.row, false)">
                {{ scope.row.basePicture }}
              </BaseViewBtn>
            </template>
          </Cell>
          <!-- baseSapStandardPrice -->
          <Cell
            v-if="cellIsShow.IsBaseSapStandardPrice"
            :label="$t('FdData.baseSapStandardPrice')"
            prop="baseSapStandardPrice"
            sort="number"
          />
          <!-- basePrice -->
          <Cell
            v-if="cellIsShow.IsBasePrice"
            :label="$t('FdData.basePrice')"
            prop="basePrice"
            sort="number"
          />
          <!-- baseTecCost -->
          <Cell
            v-if="cellIsShow.IsBaseTecCost"
            :label="$t('FdData.baseTecCost')"
            prop="baseTecCost"
            sort="number"
          />
        </Cell>
        <!-- newProject -->
        <Cell :label="$t('FdData.newProject')">
          <!-- newPartName -->
          <Cell
            v-if="cellIsShow.IsNewPartName"
            :label="$t('FdData.newPartName')"
            prop="newPartName"
            sort
            :width="150"
          />
          <!-- newPartNo -->
          <Cell
            v-if="cellIsShow.IsNewPartNo"
            :label="$t('FdData.newPartNo')"
            prop="newPartNo"
            sort
            :width="150"
          />
          <!-- commodity -->
          <Cell
            v-if="cellIsShow.IsNewCommodity"
            :label="$t('FdData.commodity')"
            prop="commodity"
            sort
          />
          <!-- newTempPartNo -->
          <Cell
            v-if="cellIsShow.IsNewTempPartNo"
            :label="$t('FdData.newTempPartNo')"
            prop="newTempPartNo"
            sort
          />
          <!-- newMaterialGroup -->
          <Cell
            v-if="cellIsShow.IsNewMaterialGroup"
            :label="$t('FdData.MaterialGroup')"
            prop="newMaterialGroup"
            sort
          />
          <!-- newMaterialDetail -->
          <Cell
            v-if="cellIsShow.IsNewMaterialDetail"
            :label="$t('FdData.MaterialDetail')"
            prop="newMaterialDetail"
            sort
          />
          <!-- newMaterialColor -->
          <Cell
            v-if="cellIsShow.IsNewMaterialColor"
            :label="$t('FdData.newMaterialColor')"
            prop="newMaterialColor"
            sort
          />
          <!-- newSize -->
          <Cell
            v-if="cellIsShow.IsNewSize"
            :label="$t('FdData.newSize')"
            prop="newSize"
            sort="number"
          />
          <!-- newQty -->
          <Cell
            v-if="cellIsShow.IsNewQty"
            :label="$t('FdData.newQty')"
            prop="newQty"
            sort="number"
          />
          <!-- newIdProcess -->
          <Cell
            v-if="cellIsShow.IsNewIdProcess"
            :label="$t('FdData.newIdProcess')"
            prop="newIdProcess"
            sort
          />
          <!-- newSupplier -->
          <Cell
            v-if="cellIsShow.IsNewSupplier"
            :label="$t('FdData.newSupplier')"
            prop="newSupplier"
            sort
          />
          <!-- newSupplierPn -->
          <Cell
            v-if="cellIsShow.IsNewSupplierPn"
            :label="$t('FdData.newSupplierPn')"
            prop="newSupplierPn"
            sort
          />
          <!-- newTooling -->
          <Cell
            v-if="cellIsShow.IsNewTooling"
            :label="$t('FdData.newTooling')"
            prop="newTooling"
            sort
          >
            <template slot-scope="scope">
              <span>{{ scope.row.newTooling ? 'Y' : 'N' }}</span>
            </template>
          </Cell>
          <!-- newRemark -->
          <Cell v-if="cellIsShow.IsNewRemark" :label="$t('FdData.newRemark')" prop="newRemark" />
          <!-- newViewPic -->
          <Cell v-if="cellIsShow.IsNewViewPic" :label="$t('FdData.newViewPic')" prop="newPicture">
            <template slot-scope="scope">
              <BaseViewBtn @click="fdPicList(scope.row, true)">
                {{ scope.row.newPicture }}
              </BaseViewBtn>
            </template>
          </Cell>
          <!-- newSapStandardPrice -->
          <Cell
            v-if="cellIsShow.IsNewSapStandardPrice"
            :label="$t('FdData.newSapStandardPrice')"
            prop="newSapStandardPrice"
            sort="number"
          />
          <!-- newPrice -->
          <Cell
            v-if="cellIsShow.IsNewPrice"
            :label="$t('FdData.newPrice')"
            prop="newPrice"
            sort="number"
          />
          <!-- newTecCost -->
          <Cell
            v-if="cellIsShow.IsNewTecCost"
            :label="$t('FdData.newTecCost')"
            prop="newTecCost"
            sort="number"
          />
        </Cell>
        <!-- statusCompare -->
        <Cell
          v-if="cellIsShow.IsStatusCompare"
          :label="$t('FdData.statusCompare')"
          prop="statusCompare"
          sort="number"
        />
        <!-- gapType -->
        <Cell
          v-if="cellIsShow.IsGapType"
          :label="$t('FdData.gapType')"
          prop="gapType"
          sort="number"
        />
        <!-- gapReason -->
        <Cell v-if="cellIsShow.IsGapReason" :label="$t('FdData.gapReason')" prop="gapReason" />
        <!-- gcm -->
        <Cell :label="$t('FdData.gcm')">
          <!-- gcmFunction -->
          <Cell :label="$t('FdData.gcmFunction')" prop="gcmFunction" sort />
          <!-- commodity -->

          <Cell :label="$t('FdData.commodity')" sort>
            <template slot-scope="scope">
              <BaseDblClick :scope="scope" @updateCell="updateCommodity">
                <template slot="one">
                  {{ scope.row.commodity }}
                </template>
                <template slot="two">
                  <el-select
                    v-model="scope.row.commodity"
                    v-focus
                    clearable
                    filterable
                    :placeholder="$t('select.placeholder')"
                    @change="changeCommodity(scope)"
                  >
                    <el-option
                      v-for="item in $store.getters['commodity/getCommodityCollectsByGcmFunction'](
                        scope.row.gcmFunction
                      )"
                      :key="item.name"
                      :label="item.name"
                      :value="item.name"
                    >
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #b4b4b4; font-size: 12px">
                        {{ item.gcmFunction }}
                      </span>
                    </el-option>
                  </el-select>
                </template>
              </BaseDblClick>
            </template>
          </Cell>
          <!-- GcmOwner -->

          <Cell :label="$t('FdData.gcmOwner')" sort>
            <template slot-scope="scope">
              <BaseDblClick :scope="scope" @updateCell="updateGcmOwner">
                <template slot="one">
                  {{ gcmOwnerById(scope.row.gcmOwner) }}
                </template>
                <template slot="two">
                  <el-select
                    v-model="scope.row.gcmOwner"
                    v-focus
                    clearable
                    :disabled="!scope.row.commodity"
                    filterable
                    :placeholder="$t('select.placeholder')"
                  >
                    <el-option
                      v-for="item in gcmOwnerList(scope.row.commodity)"
                      :key="item.userId"
                      :label="item.userName"
                      :value="item.userId"
                    >
                      <span style="float: left">{{ item.userName }}</span>
                      <span style="float: right; color: #b4b4b4; font-size: 12px">
                        {{ item.gcmFunction }}
                      </span>
                    </el-option>
                  </el-select>
                </template>
              </BaseDblClick>
            </template>
          </Cell>
          <!-- gcmCost -->
          <!-- <Cell
            v-if="cellIsShow.IsGcmCost"
            :label="$t('FdData.gcmCost')"
            prop="gcmCost"
            sort="number"
          /> -->
          <!-- gcmCostDelta -->
          <Cell
            v-if="cellIsShow.IsGcmTotalCostDelta"
            :label="$t('FdData.gcmTotalCostDelta')"
            prop="gcmTotalCostDelta"
            sort="number"
          />
          <!-- gcmCostRemark -->
          <Cell
            v-if="cellIsShow.IsGcmCostRemark"
            :label="$t('FdData.gcmCostRemark')"
            prop="gcmCostRemark"
          />
        </Cell>
        <!-- pirDelta -->
        <!-- <Cell
          v-if="cellIsShow.IsPirDelta"
          :label="$t('FdData.pirDelta')"
          prop="pirDelta"
          sort="number"
        /> -->
      </VirtualTable>
    </div>

    <!--图片对话框-->
    <BaseDialog
      v-if="picDialogVisible"
      title="图片查看"
      :visible.sync="picDialogVisible"
      width="35%"
    >
      <BaseIdpPicView
        :idp-token="idpToken"
        :pic-list="picList"
        @cancel="picDialogVisible = false"
      />
    </BaseDialog>
    <!--TODO: 设置显示列对话框 -->
    <BaseDialog
      v-if="setDialogVisible"
      title="设置显示列"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <FdCellShowSet
        :cellIsShow="cellIsShow"
        :pageId="pageId"
        @cancel="setDialogVisible = false"
        @saveOperationData="saveOperationData"
      />
    </BaseDialog>
  </div>
</template>
<script>
import { fdApproveCommit } from '@/api/quote/fd'
import { gcmOwnerCommodityMpList } from '@/api/quote/gcmOwner-cmty'
import { rdgcmList } from '@/api/quote/rdgcm'
import { fdApproveSaveSingle } from '@/api/quote/fd'
import { idpGetToken } from '@/api/quote/idp'
import { fdRowPictureList } from '@/api/quote/fd-row-picture'
import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'
import FdCellShowSet from '../../components/FdCellShowSet'
import fdCell from '@/mixins/fdCell'
export default {
  name: 'FdFocalPane',
  components: { VirtualTable, Cell, FdCellShowSet },
  mixins: [fdCell],
  props: {
    inputData: {
      default: () => null,
      type: Object
    },
    shareDataList: {
      default: () => [],
      type: Array
    }
  },
  data() {
    return {
      // gcm function 映射表
      gcmFunctionMp: [],
      // gcmOwner、Commodity映射关系
      gcmOwnerCommodityMp: [],
      // 当前用户的gcmFunction对应的所有gcmList
      gcmList: [],
      // idp token
      idpToken: '',
      // 每一行的图片数据
      picList: [],
      // 图片对话框可见标识
      picDialogVisible: false,
      // 合计信息
      totalResult: {
        totalLen: 0,
        currentLen: 0,
        basePrice: 0,
        gcmCost: 0,
        gcmCostDelta: 0
      },
      // 未完成分配列表
      unDoneAssignList: [],
      setDialogVisible: false,
      pageId: 'FdFocalPane'
    }
  },
  computed: {
    tableListFilter() {
      const sessionPost = this.$store.getters['post/getSessionPost']
      return this.shareDataList.filter(item => {
        if (!item.gcmFunction) return false
        return (
          item.gcmFunction.toLowerCase() === sessionPost.gcmFunction.toLowerCase() &&
          !item.isGcmCost
        )
      })
    }
  },

  mounted() {
    this.pageDataInit()
    this.getRdgcmList()
    this.getGcmList()
  },

  methods: {
    rowStyle(index, row) {
      if (this.unDoneAssignList.find(item => item.fdRowId === row.fdRowId)) {
        return {
          backgroundColor: '#ffdada'
        }
      }
    },
    async pageDataInit() {
      try {
        this.getIdpGetToken()
        this.$store.dispatch('commodity/initCommodityCollectsLazy')
        const mpListRes = await gcmOwnerCommodityMpList({})
        this.gcmOwnerCommodityMp = mpListRes.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取gcm function 映射表
    async getRdgcmList() {
      const res = await rdgcmList({})
      this.gcmFunctionMp = res.data
    },

    // 保存全部匹配结果
    async fdSaveAll() {
      try {
        await this.$confirmBox(this.$t('button.submit'), 'success')
        this.unDoneAssignList = this.tableListFilter.filter(
          item => !item.gcmOwner || !item.commodity
        )
        if (this.unDoneAssignList.length > 0) {
          return this.$message({
            message: '分配未完成',
            type: 'error',
            duration: 1500
          })
        }
        await fdApproveCommit(
          { fdId: this.inputData.fdId, version: this.inputData.version },
          { msgSuccess: true, msgError: true }
        )
        this.$emit('cancel')
      } catch (error) {
        console.log(error)
      }
    },

    // 获取当前登录用户的gcmFunction所有gcmList
    getGcmList() {
      const gcmFunction = this.$store.getters['post/getSessionPost'].gcmFunction
      this.gcmList = this.$store.getters['user/getUserSimpleCollectsByGcmFunction'](gcmFunction)
    },

    gcmOwnerList(commodity) {
      if (!commodity) return this.gcmList
      // {commodity:xxx,gcmOwner:xxxx}，相同commodity的list集合
      const gcmOwnerFilterList = this.gcmOwnerCommodityMp
        .filter(item => item.commodity === commodity)
        .map(item => item.gcmOwner)
      // 通过gcmOwner在gcmList找出每个人的具体信息
      const result = gcmOwnerFilterList.map(item => {
        const gcm = this.gcmList.find(gcm => gcm.userId === item)
        return gcm || { userId: '' }
      })
      return result.length > 0 ? result : this.gcmList
    },

    changeCommodity(data) {
      const commodity = data.row.commodity

      if (commodity) {
        // {commodity:xxx,gcmOwner:xxxx}，相同commodity的list集合
        const gcmOwnerFilterList = this.gcmOwnerCommodityMp
          .filter(item => item.commodity === commodity)
          .map(item => item.gcmOwner)

        // 通过gcmOwner在gcmList找出每个人的具体信息
        const result = gcmOwnerFilterList.map(item => {
          const gcm = this.gcmList.find(gcm => gcm.userId === item)
          return gcm || { userId: '' }
        })

        data.row.gcmOwner = result[0].userId || ''
      } else {
        data.row.gcmOwner = ''
      }
    },

    afterUpdate(data) {
      const fdRowId = data.row.fdRowId

      const index = this.shareDataList.findIndex(item => item.fdRowId === fdRowId)

      this.shareDataList[index] = data.row

      this.$emit('update')
    },

    async updateCommodity(data) {
      try {
        await fdApproveSaveSingle({
          commodity: data.row.commodity,
          fdRowId: data.row.fdRowId,
          gcmOwner: data.row.gcmOwner
        })
        this.afterUpdate(data)
      } catch (error) {
        console.log(error)
      }
    },

    async updateGcmOwner(data) {
      try {
        await fdApproveSaveSingle({
          commodity: data.row.commodity,
          fdRowId: data.row.fdRowId,
          gcmOwner: data.row.gcmOwner
        })
        this.afterUpdate(data)
      } catch (error) {
        console.log(error)
      }
    },

    async getIdpGetToken() {
      try {
        const idpTokenRes = await idpGetToken({})
        this.idpToken = idpTokenRes.data.accessToken
      } catch (error) {
        console.log(error)
      }
    },

    // 查看fd每一行图片列表
    async fdPicList(data, isNew) {
      const res = await fdRowPictureList({ fdRowId: data.fdRowId, isNew: isNew })
      this.picList = res.data
      this.picDialogVisible = true
    },

    totalCb(args) {
      this.totalResult = { ...args }
    }
  }
}
</script>
<style lang="scss" scoped>
.fd-focal-pane {
  .custom-top {
    width: calc(100% - 17px);
    height: 80px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .btn {
      margin-top: 15px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
  .custom-bottom {
    position: absolute;
    top: 80px;
    bottom: 0;
    left: 20px;
    right: 25px;
    .el-select {
      /deep/ .el-input {
        height: 100%;
        line-height: 23px !important;
      }
      /deep/.el-input__icon {
        line-height: unset !important;
      }
      /deep/input {
        height: 100% !important;
        border: none;
      }
    }
  }
}
</style>
